<?php

namespace app\admin\controller\count;

use app\admin\controller\goods\Goods;
use app\common\library\Email;
use app\common\model\goods\Goods as GoodsModel;
use app\common\controller\Backend;
use think\Db;
use think\Validate;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Shopmonitor extends Backend
{
    
    /**
     * Monitor模型对象
     * @var \app\common\model\count\Monitor
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\count\Shopmonitor();

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['goods','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['goods','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','stock_num','createtime','is_monitor','is_error','upper_num','keep_num','error_msg']);
                $row->visible(['goods']);
				$row->getRelation('goods')->visible(['title','specs','number']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function change($ids){
        $row = $this->model->find($ids);
        if($row){
            if($row['is_monitor'] == 1){
                $data = array(
                  'is_monitor'=>0,
                );
            }else{
                $data = array(
                    'is_monitor'=>1,
                );
            }
            $res = $this->model->save($data,array('id'=>$ids));
            if($res){
                $this->success('设置成功');
            }
        }
        $this->error('异常');
    }
    public function changes($ids){
        $row = $this->model->find($ids);
        if($row){
            if($row['is_error'] == 1){
                $data = array(
                    'is_error'=>0,
                );
            }else{
                $data = array(
                    'is_error'=>1,
                );
            }
            $res = $this->model->save($data,array('id'=>$ids));
            if($res){
                $this->success('设置成功');
            }
        }
        $this->error('异常');
    }
    public function add(){
        $ids = input('ids');
        $idsarr = explode('-',$ids);
        if ($this->request->isAjax())
        {
            $params = input('row/a','');
            $storehouse_id = $params['storehouse_id'];
            $event = json_decode($params['event'],true);

            if(!$storehouse_id){
                $this->error('未选择仓库');
            }
            $data = [];
            foreach ($event as $v){
                if(empty($v['stock_num']) && empty($v['upper_num']) && empty($v['keep_num'])){
                    $this->error('阀值或滞留时间不能为空不能为空');
                }
                $row = $this->model->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$storehouse_id))->find();
                if($row){
                    $grow = GoodsModel::get($v['goods_id']);
                    $this->error($grow['title'].'已设置预警');
                }
                $data[] = array(
                    'goods_id'=>$v['goods_id'],
                    'storehouse_id'=>$storehouse_id,
                    'stock_num'=>$v['stock_num'],
                    'upper_num'=>$v['upper_num'],
                    'keep_num'=>$v['keep_num'],
                );
            }

            $res = $this->model->saveAll($data);
            if($res){
                $this->success('添加成功');
            }
            $this->error('添加失败');
            exit;
        }

        $json = [];
        foreach ($idsarr as $v){
            $json[] = array(
               'goods_id'=>$v,
               'stock_num'=>0,
            );
        }

        $glist = Db::name('goods')->where(array('id'=>array('in',$idsarr)))->select();
        $this->assign('glist',$glist);
        $this->assign('json',json_encode($json));
        return $this->view->fetch();
    }
    public function checkerror(){
        $num = $this->model->where(array('is_error'=>1))->count();
        if($num){
            $this->success();
        }else{
            $this->error();
        }
    }


    protected function sendemail(){
        $row = $this->request->post('row/a');
        $receiver = $this->request->post("receiver");
        if ($receiver) {
            if (!Validate::is($receiver, "email")) {
                $this->error(__('Please input correct email'));
            }
            \think\Config::set('site', array_merge(\think\Config::get('site'), $row));
            $email = new Email;
            $result = $email
                ->to($receiver)
                ->subject(__("This is a test mail"))
                ->message('<div style="min-height:550px; padding: 100px 55px 200px;">' . __('This is a test mail content') . '</div>')
                ->send();
            if ($result) {
                $this->success();
            } else {
                $this->error($email->getError());
            }
        } else {
            return $this->error(__('Invalid parameters'));
        }
    }
}
